import cv2
import requests
import numpy as np
import pygame
import threading
class MJPEG_Bridge:
    def __init__(self,url,img_Size=(360,1280)):
        self.url=url
        self.image=np.ones(img_Size)*100
        self.imgSize=img_Size
        self.streaming=False
    def Start(self):
        self.streaming=True
        t=threading.Thread(target=self.Get_Image,args=())
        t.setDaemon(True)
        t.start()
    def Stop(self):
        self.streaming=False

    def Get_Image(self):
        while self.streaming:
            try:
                r = requests.get(self.url, stream=True)
                if (r.status_code == 200):
                    bytes = b''
                    for chunk in r.iter_content(chunk_size=1024):
                        if not self.streaming:break
                        bytes += chunk
                        a = bytes.find(b'\xff\xd8')
                        b = bytes.find(b'\xff\xd9')
                        if a != -1 and b != -1:
                            jpg = bytes[a:b + 2]
                            bytes = bytes[b + 2:]
                            image = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.IMREAD_COLOR)
                            [height, width, pixels] = image.shape
                            image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
                            image=cv2.resize(image,(self.imgSize[1],self.imgSize[0]))
                            self.image=cv2.flip(cv2.transpose(image),1)
                else:
                    print("Received unexpected status code {}".format(r.status_code))
            except:
                continue

